package top.dopen.home.work.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import top.dopen.home.work.common.WechatValidate;
import top.dopen.home.work.entity.WeChatTextMessage;

import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>
 * 消息控制器
 * </p>
 *
 * @Auther Dopen
 * @Date 2020/8/4
 */
@ApiIgnore
@Slf4j
@RestController
@RequestMapping("/notify")
public class ExampleMessageController {

	@Resource
	private WechatValidate wechatValidate;

	/**
	 * 消息效验
	 * @param sign
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @return
	 */
	@GetMapping("getMessage")
	public ResponseEntity<String> getMessageValidate(
			@RequestParam("msg_signature") String sign,
			@RequestParam("timestamp") String timestamp,
			@RequestParam("nonce") String nonce,
			@RequestParam("echostr") String echostr){
		if(StringUtils.isAnyBlank(sign,timestamp,nonce,echostr)){
			return new ResponseEntity<>("参数有误",HttpStatus.BAD_REQUEST);
		}
		String s = wechatValidate.validateUrl(sign, timestamp, nonce, echostr);
		return new ResponseEntity<>(s, HttpStatus.OK);


	}

	/**
	 * 微信被动消息
	 * @param data
	 * @param sign
	 * @param timestamp
	 * @param nonce
	 * @return
	 * @throws JsonProcessingException
	 */
	@ApiIgnore
	@PostMapping("getMessage")
	public ResponseEntity<String> getMessage(
			@RequestBody String data,
			@RequestParam("msg_signature") String sign,
			@RequestParam("timestamp") String timestamp,
			@RequestParam("nonce") String nonce) throws JsonProcessingException {
		Map<String, String> map = wechatValidate.decryptBody(sign, timestamp, nonce, data);
		WeChatTextMessage weChatTextMessage = new WeChatTextMessage();
		weChatTextMessage.setToUserName(map.get("FromUserName"));
		weChatTextMessage.setFromUserName(map.get("ToUserName"));
		weChatTextMessage.setCreateTime(String.valueOf(System.currentTimeMillis()));
		weChatTextMessage.setMsgType("text");
		if("你好".equals(map.get("Content"))){
			weChatTextMessage.setContent("您也好");
		}else{
			weChatTextMessage.setContent("请您联系客服");
		}
		XmlMapper mapper = new XmlMapper();
		String s = mapper.writeValueAsString(weChatTextMessage);
		log.info("被动回复未加密内容：{}",s);
		s = wechatValidate.messageSign(s);
		log.info("被动回复加密内容：{}",s);
		return new ResponseEntity<>(s,HttpStatus.OK);
	}


}
